package com.user.web;

import com.user.config.JwtProperties;
import com.user.entity.Payload;
import com.user.entity.ResultBody;
import com.user.entity.User;
import com.user.entity.UserInfo;
import com.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties properties;
    @GetMapping("/check/{data}/{type}")
    public ResultBody checkUserData(@PathVariable("data") String data,@PathVariable(value="type") Integer type){
        boolean b = userService.checkData(data, type);
        return ResultBody.creatResult(200,b,b?"可用":"不可用");
    }

    @PostMapping("/code")
    public ResultBody sendCode(@RequestParam("phone") String phone){
        String code = userService.sendeCode(phone);
        return ResultBody.creatResult(200,!StringUtils.isEmpty(code),code);
    }

    @PostMapping("/register")
    public ResultBody register(User user,@RequestParam String code){
        boolean b = userService.register(user, code);
        return ResultBody.creatResult(200,b,b?"注册成功":"注册失败");
    }
    @PostMapping("/query")
    public ResultBody queryUserByName(@RequestParam String username,@RequestParam String password){
        return userService.queryUserByName(username,password);
    }
    //jwt形式的用户登录
    @PostMapping("/login")
    public ResultBody login(@RequestParam("username") String username,
                            @RequestParam("password") String password,
                            HttpServletResponse response){
        String token = userService.login(username, password);
        if(token != null){
            Cookie cookie = new Cookie(properties.getTokenProper().getCookieName(),token);
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            return null;
        }
        return ResultBody.creatResult(200,false,"登录失败");
    }
    //jwt形式校验用户是否登录
    @GetMapping("/verify")
    public ResultBody verifyUser(HttpServletRequest request, HttpServletResponse response){
        Payload<UserInfo> data = userService.verifyUser(request,response);
        return ResultBody.creatResult(200,true,data);
    }
    //退出登录
    @GetMapping("/logout")
    public ResultBody logout(HttpServletRequest request, HttpServletResponse response){
        userService.logout(request,response);
        return ResultBody.creatResult(200,true,"退出登录成功");
    }
}
